package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

func openFile(fileName string) string {
	var str [1024]byte
	var fileStr string
	fileObj, err := os.Open("../../public/index.html")
	if err != nil {
		fmt.Printf("open file, err: %v\n", err)
	}
	defer fileObj.Close()

	for {
		n, err := fileObj.Read(str[:])
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Printf("err: %v\n", err)
		}
		fileStr += string(str[:n])
	}
	return fileStr
}

// 解析get请求 无query参数
func fun(w http.ResponseWriter, r *http.Request) {
	str := openFile("../public/index.html")
	w.Write([]byte(str))
}

// 解析query参数
func fun2(w http.ResponseWriter, r *http.Request) {
	fmt.Printf("URL: %v\n", r.URL)
	fmt.Printf("Method: %v\n", r.Method)
	fmt.Println(ioutil.ReadAll(r.Body))
	// 带有query参数
	arr := r.URL.Query()
	fmt.Println("name:", arr.Get("name"), " age:", arr.Get("age"))

	w.Write([]byte("ok"))
}

func main() {

	fmt.Println("server running ...")
	http.HandleFunc("/", fun)
	http.HandleFunc("/static", fun2)

	http.ListenAndServe("127.0.0.1:8001", nil)

	/*
		get请求1：http://127.0.0.1:8001/static
			r.URL 		url: /static
			r.Method 	method: GET
			r.Body 		[] <nil>
		get请求2（带query参数）：http://127.0.0.1:8001/static?name=lisi&age=14
		r.URL.Query() 自动解析query参数为 map 参数，get方法可以解析单个query参数
			r.URL 				url: /static?name=lisi&age=14
			r.URL.Query() 	map[age:[14] name:[lisi]]
			r.Method 			method: GET
			r.Body 				[] <nil>
	*/
}
